package com.thinkfit.jy.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.blankj.utilcode.util.ToastUtils;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.LoginActivity;
import com.thinkfit.jy.activity.MainActivity;
import com.thinkfit.jy.activity.WarmUpVideoActivity;
import com.thinkfit.jy.serialport.SerialPortManager;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

/**
 * 返回按钮（用于在第三方应用中返回本应用）
 */
public class DialogViewUtils implements View.OnClickListener {

    private static DialogViewUtils dialogViewUtils;
    WindowManager windowManager;

    boolean isFist = true;
    TextView tvTitle,tvInfo,tvLeft,tvRight;
    ConstraintLayout clBg;
    Context mContext;
    View inflate;
    boolean isToMain;
    boolean isClose;
    int mType;
    String packageName,openPackageName;
    public static final int EXIT_SPORT = 0;//退出运动
    public static final int TOURIST_PATTERN = 1;//游客模式
    public static final int EXIT_LOGOUT = 2;//退出登录
    public static final int EXIT_APP = 3;//退出应用
    public static final int BLUETOOTH_DISCONNECTED = 4;//蓝牙连接断开
    public static final int SPORT_START = 5;//开始运动
    public static final int WARM_UP_END = 6;//热身结束

    public static DialogViewUtils getInstance(){
        if(dialogViewUtils == null){
            dialogViewUtils = new DialogViewUtils();
        }
        return dialogViewUtils;
    }

    public void initView(Context context,boolean isToMain,int type){
        mContext = context;
        mType = type;
        this.isToMain = isToMain;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.item_dialog, null);
            tvTitle = inflate.findViewById(R.id.tv_title);
            tvInfo = inflate.findViewById(R.id.tv_info);
            tvLeft = inflate.findViewById(R.id.tv_left);
            tvRight = inflate.findViewById(R.id.tv_right);
            clBg = inflate.findViewById(R.id.cl_bg);

            tvLeft.setOnClickListener(this);
            tvRight.setOnClickListener(this);
            clBg.setOnClickListener(this);
        }
        tvLeft.setVisibility(View.VISIBLE);
        if(type == EXIT_SPORT){
            tvTitle.setText(mContext.getString(R.string.app_dialog_stop_exercise_title));
            tvInfo.setText(mContext.getString(R.string.app_sure_end_sport));
            tvRight.setText(mContext.getString(R.string.app_ok));
            tvLeft.setText(mContext.getString(R.string.app_cancel));
        }else if(type == TOURIST_PATTERN){
            tvTitle.setText(mContext.getString(R.string.app_dialog_guest_mode_title));
            tvInfo.setText(mContext.getString(R.string.app_records_not_saved));
            tvRight.setText(mContext.getString(R.string.app_login));
            tvLeft.setText(mContext.getString(R.string.app_cont));
        }else if(type == EXIT_LOGOUT){
            tvTitle.setText(mContext.getString(R.string.app_logout));
            tvInfo.setText(mContext.getString(R.string.app_are_you_sure_logout));
            tvRight.setText(mContext.getString(R.string.app_ok));
            tvLeft.setText(mContext.getString(R.string.app_cancel));
        }else if(type == EXIT_APP){
            tvTitle.setText(mContext.getString(R.string.app_dialog_exit_app_title));
            tvInfo.setText(mContext.getString(R.string.app_are_you_sure_app_out));
            tvRight.setText(mContext.getString(R.string.app_ok));
            tvLeft.setText(mContext.getString(R.string.app_cancel));
        }else if(type == BLUETOOTH_DISCONNECTED){
            tvTitle.setText(mContext.getString(R.string.app_dialog_stop_exercise_title));
            tvInfo.setText(mContext.getString(R.string.app_dialog_device_connection_hint));
            tvRight.setText(mContext.getString(R.string.app_ok));
            tvLeft.setVisibility(View.GONE);
            BluetoothOrder.getInstance().isHeartRateConnect(false);
        }else if(type == SPORT_START){
            tvTitle.setText(mContext.getString(R.string.app_dialog_stop_exercise_title));
            tvInfo.setText(mContext.getString(R.string.app_dialog_device_connection_hint));
            tvRight.setText(mContext.getString(R.string.app_dialog_start_sport_hint));
            tvLeft.setText(mContext.getString(R.string.app_dialog_warm_up_hint));
        }else if(type == WARM_UP_END){
            tvTitle.setText(mContext.getString(R.string.app_dialog_stop_exercise_title));
            tvInfo.setText(mContext.getString(R.string.app_dialog_warn_up_end_hint));
            tvRight.setText(mContext.getString(R.string.app_dialog_start_sport_hint));
            tvLeft.setText(mContext.getString(R.string.app_cancel));
        }

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        layoutParams.gravity = Gravity.CENTER;

        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cl_bg:
                goneLayout();
                break;
            case R.id.tv_left:
                goneLayout();
                if(mType == TOURIST_PATTERN){
                    if(DeviceTypeUtils.getInstance().isTreadmill()){
                        if(DeviceTypeUtils.connectDeviceType() == 0){
                            BluetoothOrder.getInstance().startTreadmill();
                        }else {
                            SerialPortManager.getInstance().startRun();
                        }
                    }else{
                        CountDownViewUtils.getInstance().initView(mContext,3);
                    }
//                    CountDownViewUtils.getInstance().initView(mContext,3);
                }else if(mType == SPORT_START){
                    //热身
                    Intent intent = new Intent(mContext, WarmUpVideoActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                    SportsStatusBarViewUtils.getInstance().goneLayout();
                    goneLayout();
                }else if(mType == WARM_UP_END){
                    //热身结束
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.KILL_ACTIVITY,"");
                    EventBus.getDefault().post(map);
                    goneLayout();
                }
                break;
            case R.id.tv_right:
                if(mType == TOURIST_PATTERN){
                    DataManager.Companion.getInstance().saveSetTarget(null);
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                    goneLayout();
                }else if(mType == EXIT_LOGOUT){
                    DataManager.Companion.getInstance().logout();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.TO_HOME_ACTIVITY,"");
                    EventBus.getDefault().post(map);
                    goneLayout();
                }else if(mType == EXIT_APP){
                    if(!TextUtils.isEmpty(packageName)){
                        DeviceTypeUtils.getInstance().killApp(mContext,getPackageName());
                        ApkListViewUtils.getInstance().setOpenStatus(getPackageName(),false);
                        packageName = "";
                    }else {
                        ToastUtils.showShort(mContext.getString(R.string.app_not_running));
                    }
                    if(isClose){
                        if(!TextUtils.isEmpty(openPackageName)){
                            isOpenApk();
                            isClose = false;
                        }
                    }
                    goneLayout();
                    ApkListViewUtils.getInstance().goneButton();
                }else if(mType == BLUETOOTH_DISCONNECTED){
//                    HashMap<String, Object> map = new HashMap<>();
//                    map.put(EventBusEvent.STOP_RUN, 0);
//                    EventBus.getDefault().post(map);
                    goneLayout();
                }else if(mType == SPORT_START || mType == WARM_UP_END){
                    //开始运动
                    if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                        ToastUtils.showShort(R.string.app_device_connect);
                        return;
                    }
                    if(DeviceTypeUtils.getInstance().isTreadmill()){
                        if(DeviceTypeUtils.connectDeviceType() == 0){
                            BluetoothOrder.getInstance().startTreadmill();
                        }else {
                            SerialPortManager.getInstance().startRun();
                        }
                    }
//                    CountDownViewUtils.getInstance().initView(mContext,3);
                    goneLayout();
                    if(DataManager.Companion.getInstance().isLogin()){

                    }else {

                    }

                }else {
//                    if (SerialPortManager.getInstance().isRun() || BluetoothOrder.getInstance().isRun()) {//判断是否有在运行
//                        stopDevice();
//                        goneLayout();
//                        HashMap<String, Object> map = new HashMap<>();
//                        map.put(EventBusEvent.KILL_ACTIVITY,"");
//                        EventBus.getDefault().post(map);
//                    }
                    if(!MotionDataUtils.getInstance().isStop()){
                        if(DataManager.Companion.getInstance().isLogin()){
                            LoadViewUtils.getInstance().initView(mContext,R.string.sports_stopped);
                        }else {
                            LoadViewUtils.getInstance().setContext(mContext);
                        }
                        stopDevice();
                        goneLayout();
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(EventBusEvent.KILL_ACTIVITY,"");
                        EventBus.getDefault().post(map);
                    }

                    if(!isToMain){
                        return;
                    }
                    if(!SystemUtils.isForeground(mContext,mContext.getPackageName())){
//                    Intent intent = new Intent();
//                    ComponentName componentName = new
//                            ComponentName(mContext.getPackageName(), MainActivity.class.getName());
////                        ComponentName("com.thinkfit.ride",activityName);
//                    intent.setComponent(componentName);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    mContext.startActivity(intent);
                        SystemUtils.setTopApp(mContext,mContext.getPackageName());

                        HashMap<String, Object> map = new HashMap<>();
                        map.put(EventBusEvent.TO_MAIN,0);
                        EventBus.getDefault().post(map);

                        System.out.println("ddddddddddddddddddddddd  inflate GONE");
//                    inflate.setVisibility(View.GONE);
                        ShowSpeedViewUtils.getInstance().goneLayout();
//                    BackButtonViewUtils.getInstance().goneButton();
//                        SportsStatusBarViewUtils.getInstance().atThirdParty(false);
                        SportsStatusBarViewUtils.getInstance().setHomeView(false);
                    }else {
                        Intent intent = new Intent(mContext, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent);
                    }
                }
                break;
        }
    }

    public String getPackageName(){
        return packageName;
    }

    public void setClosePackageName(String packageName){
        this.packageName = packageName;
    }

    public void setOpenPackageName(String packageName){
        openPackageName = packageName;
    }

    public void setIsCloseDialog(boolean isClose){
        this.isClose = isClose;
    }

    public void isOpenApk(){
        PackageManager packageManager = mContext.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(openPackageName);
        if (intent != null) {
            mContext.startActivity(intent);
        }
        ApkListViewUtils.getInstance().setOpenStatus(openPackageName,true);
    }

    public void stopDevice(){
        if(!(SerialPortManager.getInstance().isConnected() || BluetoothOrder.getInstance().isConnect())){
            System.out.println("ddddddddddddddddddddddd   未连接设备");
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){//判断连接类型
            BluetoothOrder.getInstance().closeRxJavaClone();
            BluetoothOrder.getInstance().closeTreadmillStateDisposable();
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备暂停");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().pauseTreadmill();
                }else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_PAUSE);
                }

            }else {
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备停止");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().stopTreadmill();
                } else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_STOP);
                }

            }
        }else {
            System.out.println("ddddddddddddddddddddddd   串口通知设备停止");
            SerialPortManager.getInstance().stopRun();
        }
    }

    public void goneLayout(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
            }
        }

    }

    public void invaliView(){
        if(inflate != null){
            windowManager.removeView(inflate);
            isFist = true;
            windowManager = null;
            inflate = null;
        }
    }

}
